﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using Openfree.Framework.DataAccess;

public partial class PMSWeb_TaskTracking : PMSBase
{
    private SqlCodeConfig codeConfig;
    private string cmdText  = @"select a.TaskCode,a.TaskItemID,a.TaskID,a.SNYear,a.SNGroup,a.SNTask,a.SNProject,a.SNDispatch,a.TaskState,D.CodeName as GroupName,C.Guest,C.Phone,C.Location,C.RoomNo,C.HouseNo,C.CreateDate,case when B.status='" + PMSGoodsState.NotOut + "' then '" + PMSGoodsState.GetName("" + PMSGoodsState.NotOut) + @"' when B.status='" + PMSGoodsState.IsOut + "' then '" + PMSGoodsState.GetName("" + PMSGoodsState.IsOut) + @"' else '——' end ReqStatus, (select Username from T_User where UserID=C.UserID) Username from PMS_TaskItem a 
                   left join IC_Requisition B on B.TaskID=a.TaskItemID left join PMS_TaskLX C on c.TaskID = a.TaskID left join T_CodeConfig D on D.CodeValue=a.SNGroup AND D.Category = '" + PMSCodeCategory.PMS_BMZB + "'  where 1=1  ";
    protected void Page_Load(object sender, EventArgs e)
    {
        this.TableName = "PMS_TaskItem";
        this.Key = "TaskItemID";
        if (!IsPostBack)
        {
            FillGirdView(0, cmdText + " order by a.TaskState asc,C.CreateDate desc");
            InitData();
            if (!string.IsNullOrEmpty(Request["TaskItemID"]))
            {
                this.btnView_Click(null, e);
            }
            tbPersonCode.Attributes.Add("onkeypress", "Openfree.prototype.EnterSubmit('" + tbPersonCode.ClientID + "',event);");
        }
        else
        {
            if (pnlEdit.Visible && !string.IsNullOrEmpty(tbPersonCode.Text))
            {
                TaskPersonItem.AddSelectPerson(tbPersonCode.Text);
                tbPersonCode.Text = "";
            }
            else if (pnlGrid.Visible)
                FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        }

        ValidateUser2.OnValidateUser += new EventHandler(on_ValidateUser);
    }
    public void btnSearchPerson_Click(object sender, EventArgs e)
    {
        pnlSearchPerson.Visible = true;
    }
    public void InitData()
    {
        DateTime dt = DateTime.Now;
        DepTime.Text = dt.ToString("yyyy-MM-dd");
        ArrTime.Text = dt.ToString("yyyy-MM-dd");
        ddlDepHH.Text = "00";
        ddlDepMM.Text = "00";
        ddlArrHH.Text = "00";
        ddlArrMM.Text = "00";
        //获取用户意见
        codeConfig = new SqlCodeConfig(this.Connection);
        DataSet ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_CustomerSuggest);
        radioButtonList.Items.Clear(); 
        foreach (DataRow row in ds.Tables[0].Rows)
        { 
            ListItem item = new ListItem();
            item.Text = row["CodeName"].ToString();
            item.Value = row["CodeValue"].ToString();
            radioButtonList.Items.Add(item);
        } 
        ds = codeConfig.LoadDataByCategory(PMSCodeCategory.PMS_BMZB);
        this.BindDropDownList(S_GroupID, ds, true);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        tipMessage1.ShowMessage("", 5000);
        StringBuilder sql = new StringBuilder(cmdText); 
        if (!string.IsNullOrEmpty(S_Guest.Text))
        {
            sql.Append(" AND C.Guest like '%").Append(S_Guest.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_Phone.Text))
        {
            sql.Append(" AND C.Phone = '").Append(S_Phone.Text).Append("'");
        }
        if (!string.IsNullOrEmpty(S_TaskState.SelectedValue))
        {
            sql.Append(" AND a.TaskState = '").Append(S_TaskState.SelectedValue).Append("'");
        }
        if (!string.IsNullOrEmpty(S_GroupID.SelectedValue))
        {
            sql.Append(" AND a.SNGroup = '").Append(S_GroupID.SelectedValue).Append("'");
        } 
        if (!string.IsNullOrEmpty(S_TaskCode.Text.Trim()))
        {
            sql.Append(" AND a.TaskCode = '").Append(S_TaskCode.Text.Trim()).Append("'");
        }
        if (!string.IsNullOrEmpty(S_stCreateDate.Text.Trim()))
        {
            sql.Append(" AND C.CreateDate >= CONVERT(varchar, '" + S_stCreateDate.Text.Trim() + "', 120 ) ");
        }
        if (!string.IsNullOrEmpty(S_endCreateDate.Text.Trim()))
        {
            sql.Append(" AND C.CreateDate <= CONVERT(varchar, '" + S_endCreateDate.Text.Trim() + "', 120 ) ");
        }
        sql.Append(" order by a.TaskState asc,C.CreateDate desc");
        FillGirdView(0, sql.ToString());
    }
    protected void FillGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        ViewState[this.ClientID + "cmdText"] = cmdText;
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        gridView.ShowFooter = true;
        gridView.NavigationData = splitPage.GetNavigationData(currentPage);
        gridView.DataSource = ds.Tables[0];
        gridView.DataBind();
    }

    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[1].Controls[0]).NavigateUrl = "TaskTracking.aspx?TaskItemID=" + ((HiddenField)e.Row.Cells[0].Controls[1]).Value;
            e.Row.Cells[2].Text = PMSCodeCategory.GetName(e.Row.Cells[2].Text);
            if ((Convert.ToInt32(e.Row.Cells[10].Text) == PMSTaskState.Complete))
            {
                e.Row.Cells[10].Style.Value = "Font-color:blue;";
                e.Row.Cells[10].Text = "<span style='color:blue'>已完成<span>";
            }
            else if ((Convert.ToInt32(e.Row.Cells[10].Text) == PMSTaskState.IsRemove))
            {
                e.Row.Cells[10].Style.Value = "Font-color:green;";
                e.Row.Cells[10].Text = "<span style='color:green'>已作废<span>";
                e.Row.Cells[1].Text = "<strike>" + e.Row.Cells[1].Text + "</strike>";
            }
            else
            {
                e.Row.Cells[10].Style.Value = "Font-color:red;";
                e.Row.Cells[10].Text = "<span style='color:red'>未完成<span>";
            } 
        }
    }

    protected void gridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }


    protected void btnRemove_Click(object sender, EventArgs e)
    {
        string TaskItemID = Request.Form["TaskItemID"];
        if (string.IsNullOrEmpty(TaskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        string cmdText = "select T.*,(select count(TaskID) from PMS_TaskItem where TaskID=T.TaskID) as GroupCount from PMS_TaskItem T where T.TaskItemID='{0}'";
        cmdText = string.Format(cmdText, TaskItemID);

        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);

        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow row = ds.Tables[0].Rows[0];
        //逻辑删除
        cmdText = "update PMS_TaskItem set TaskState='" + PMSTaskState.IsRemove + "' where TaskItemID='" + row["TaskItemID"].ToString() + "';";
        BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        tipMessage1.ShowMessage("成功作废", 5000);  
        return;
        
        //物理删除
        if(Convert.ToInt32(row["TaskState"]) == PMSTaskState.Complete)
        {
            Alert("您选择的任务已经完成，不能再进行作废操作！");
            return;
        }

        cmdText = @"delete from PMS_TaskItem where TaskItemID='{0}';
                        delete from PMS_TaskUser where TaskID='{0}';
                        delete from IC_RequisitionItem where RequisitionID in (select RequisitionID from IC_Requisition where TaskID='{0}');
                        delete from IC_Requisition where TaskID='{0}';";
        if (Convert.ToInt32(row["GroupCount"])==1)
        {
            cmdText += "delete from PMS_TaskLX where TaskID='" + row["TaskID"].ToString() + "'";
        }
        cmdText = string.Format(cmdText, TaskItemID);
        BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    private void ClearValue()
    {
        tbGuest.Text = "";
        tbRoomNo.Text = "";
        cbHouseNo.Text = "";
        tbPhone.Text = "";
        tbTroubleDescription.Text = "";
        lbUserID.Text = SessionManager.LoginName;
        lbOrgID.Text = SessionManager.OrgName;
        cbIsReqGood.Checked = false;
        pnlSearchPerson.Visible = false;
        lbCreateDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        this.InitData();
    }
    protected void btnView_Click(object sender, EventArgs e)
    {

        string taskItemID = Request.Form["TaskItemID"];
        if(sender==null)
            taskItemID = Request["TaskItemID"];
        if (string.IsNullOrEmpty(taskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        hfTaskID.Value = taskItemID;

        hfAddOrEdit.Value = "View";
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select (select top 1 OutTime from PMS_TaskUser where TaskID=A.TaskItemID) as OutTime,(select top 1 CustomerSuggest from PMS_TaskUser where TaskID=A.TaskItemID) as CustomerSuggest,A.*,B.Guest,B.Location,B.RoomNo,B.HouseNo,B.Phone,B.TroubleDescription,B.OrgID,B.UserID,B.CreateDate,B.IsRequestGood FROM PMS_TaskItem A inner join PMS_TaskLX B on A.TaskID=B.TaskID where A.TaskItemID='" + taskItemID + "'", this.TableName);

        SessionManager.DataSet = ds;

        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }

        pnlGrid.Visible = false;
        pnlEdit.Visible = true; 
        ClearValue();

        DataRow row = ds.Tables[0].Rows[0]; 
        if (!string.IsNullOrEmpty(row["StartTime"].ToString()) && !string.IsNullOrEmpty(row["EndTime"].ToString()))
        {
            DateTime sdt = Convert.ToDateTime(row["StartTime"].ToString());
            DepTime.Text = sdt.ToString("yyyy-MM-dd");
            ddlDepHH.Text = sdt.Hour.ToString("00");
            ddlDepMM.Text = sdt.Minute.ToString("00");
            DateTime edt = Convert.ToDateTime(row["EndTime"].ToString());
            ArrTime.Text = edt.ToString("yyyy-MM-dd");
            ddlArrHH.Text = edt.Hour.ToString("00");
            ddlArrMM.Text = edt.Minute.ToString("00");
            ddlHHdis.Text = row["OutTime"].ToString();
            radioButtonList.SelectByValue = row["CustomerSuggest"].ToString();
        }
        tbHandling.Text = row["Handling"].ToString(); 

        //显示领单人
        InitGridReceiverView(taskItemID);

        //tabsMenu.SelectedIndex = 0;

        SessionManager.DataSet = ds; 
        TaskPersonItem.ShowWorkTime = true;
        TaskPersonItem.IsReadOnly = true;
        TaskPersonItem.InitData("TaskID", taskItemID, string.Empty);
        
        UserAccess user = new UserAccess(base.Connection);
        tbGuest.Text = row["Guest"].ToString();
        tbRoomNo.Text = row["RoomNo"].ToString();
        cbHouseNo.Text = row["HouseNo"].ToString();
        tbPhone.Text = row["Phone"].ToString();
        tbTroubleDescription.Text = row["TroubleDescription"].ToString();
        lbOrgID.Text = user.GetUserOrgName(row["OrgID"].ToString());
        lbUserID.Text = user.GetUserNameByUserID(row["UserID"].ToString());
        cbIsReqGood.Checked = Convert.ToBoolean(row["IsRequestGood"]);
        lbCreateDate.Text = Convert.ToDateTime(row["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
 
        SetTaskReadOnly(true);
    }
    private void SetTaskReadOnly(bool flag)
    {
        DepTime.ReadOnly = flag;
        ArrTime.ReadOnly = flag;
        ddlHHdis.ReadOnly = flag;
        tbHandling.ReadOnly = flag;
        radioButtonList.Enabled = !flag;
        btnSelect.Visible = !flag;
        btnSave.Visible = !flag;
        btnSearchPerson.Visible = !flag; 
    }

    private void on_ValidateUser(object sender, EventArgs e)
    {
        ////0用户名密码错误，1正确，2用户被锁定
        //if ("0".Equals(sender.ToString()))
        //{
        //    tipMessage1.ShowMessage("用户名密码错误", 5000);
        //    return;
        //}

        //if ("2".Equals(sender.ToString()))
        //{
        //    tipMessage1.ShowMessage("用户被锁定", 5000);
        //    return;
        //}
        //SecurityAccess securityAccess = new SecurityAccess(base.Connection);
        //DataSet dsRule = securityAccess.GetUserRule(ValidateUser2.GetUserID());
        //if (dsRule.Tables[0].Select("ContainerName='RWDFHQR'").Length == 0)
        //{   // 授权项： RWDFHQR 任务单返还确认 
        //    tipMessage1.ShowMessage("用户权限不足", 5000);
        //    return;
        //}

        //DataSet ds = PMSAccess.GetDataSet(this.Connection, "select A.*,B.Guest,B.Location,B.Phone,B.TroubleDescription,B.OrgID,B.UserID,B.CreateDate,B.IsRequestGood FROM PMS_TaskItem A inner join PMS_TaskLX B on A.TaskID=B.TaskID where A.TaskItemID='" + taskItemID + "'", this.TableName);
        DataSet ds = PMSAccess.GetDataSet(this.Connection, "select A.*,B.Guest,B.Location,B.RoomNo,B.HouseNo,B.Phone,B.TroubleDescription,B.OrgID,B.UserID,B.CreateDate,B.IsRequestGood FROM PMS_TaskItem A inner join PMS_TaskLX B on A.TaskID=B.TaskID where A.TaskItemID='" + hfTaskID.Value + "'", this.TableName);
        SessionManager.DataSet = ds;

        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow row = ds.Tables[0].Rows[0];
        if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.Complete)
        {
            Alert("您选择的任务已经完成，不能再进行操作！");
            return;
        }
        if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.IsRemove)
        {
            Alert("您选择的任务已经作废，不能再进行操作！");
            return;
        }
        ClearValue();
        if (!string.IsNullOrEmpty(row["StartTime"].ToString()) && !string.IsNullOrEmpty(row["StartTime"].ToString()))
        {
            DateTime sdt = Convert.ToDateTime(row["StartTime"].ToString());
            DepTime.Text = sdt.ToString("yyyy-MM-dd");
            ddlDepHH.Text = sdt.Hour.ToString("00");
            ddlDepMM.Text = sdt.Minute.ToString("00");
            DateTime edt = Convert.ToDateTime(row["EndTime"].ToString());
            ArrTime.Text = edt.ToString("yyyy-MM-dd");
            ddlArrHH.Text = edt.Hour.ToString("00");
            ddlArrMM.Text = edt.Minute.ToString("00");
            ddlHHdis.Text = "" + 0;
        }
        tbHandling.Text = row["Handling"].ToString();
        SetTaskReadOnly(false);

        pnlGrid.Visible = false;
        pnlEdit.Visible = true;

        //显示领单人
        InitGridReceiverView(hfTaskID.Value);

        SessionManager.DataSet = ds;
        TaskPersonItem.ShowWorkTime = true;
        TaskPersonItem.IsReadOnly = false;
        TaskPersonItem.InitData("TaskID", hfTaskID.Value, string.Empty);

        UserAccess user = new UserAccess(base.Connection);
        tbGuest.Text = row["Guest"].ToString();
        tbRoomNo.Text = row["RoomNo"].ToString();
        cbHouseNo.Text = row["HouseNo"].ToString();
        tbPhone.Text = row["Phone"].ToString();
        tbTroubleDescription.Text = row["TroubleDescription"].ToString();
        lbOrgID.Text = user.GetUserOrgName(row["OrgID"].ToString());
        lbUserID.Text = user.GetUserNameByUserID(row["UserID"].ToString());
        cbIsReqGood.Checked = Convert.ToBoolean(row["IsRequestGood"]);
        lbCreateDate.Text = Convert.ToDateTime(row["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
    }

    protected void btnEnd_Click(object sender, EventArgs e)
    {
        tipMessage1.ShowMessage("", 5000);

        string taskItemID = Request.Form["TaskItemID"];
        if (string.IsNullOrEmpty(taskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        hfTaskID.Value = taskItemID;
        hfAddOrEdit.Value = "End";
        on_ValidateUser(sender, e);
        //ValidateUser2.ShowModalPopup();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(ddlDepHH.Text.Trim()) > 23 || Convert.ToInt32(ddlArrHH.Text.Trim()) > 23)
        {
            Alert("小时数不超过23");
            return;
        }
        if (Convert.ToInt32(ddlDepMM.Text.Trim()) > 60 || Convert.ToInt32(ddlArrMM.Text.Trim()) > 60)
        {
            Alert("分钟数不超过60");
            return;
        }
        //判断是否选择派修人员
        TaskPersonItem.ShowWorkTime = true;
        string result = TaskPersonItem.PreProcessSave();
        if (!string.IsNullOrEmpty(result))
        {
            tipMessage1.ShowMessage(result, 5000);
            return;
        }
        DataTable dt = null;
        StringBuilder str = new StringBuilder();
        if (SessionManager.DataSet.Tables.Contains(TaskPersonItem.m_TableName))
        {
            dt = SessionManager.DataSet.Tables[TaskPersonItem.m_TableName];
            foreach (DataRow dr in dt.Rows)
            {
                if (dr.RowState != DataRowState.Deleted)
                {
                    str.Append(",'").Append(dr["UserID"].ToString()).Append("'");
                    dr["TaskID"] = hfTaskID.Value;
                    dr["UserType"] = PMSCodeCategory.UserWorker;
                    dr["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    //dr["UpdateUser"] = ValidateUser2.GetUserID();
                    dr["UpdateUser"] = SessionManager.UserID;
                    dr["OutTime"] = string.IsNullOrEmpty(ddlHHdis.Text) ? 0 : Convert.ToInt32(ddlHHdis.Text);
                    dr["CustomerSuggest"] = radioButtonList.SelectedValue; 
                }
            }
        } 
        DataRow row = SessionManager.DataSet.Tables[this.TableName].Rows[0];
        row["TaskState"] = PMSTaskState.Complete;
        row["StartTime"] = DepTime.Text + " " + ddlDepHH.Text.Trim() + ":" + ddlDepMM.Text.Trim();
        row["EndTime"] = ArrTime.Text + " " + ddlArrHH.Text.Trim() + ":" + ddlArrMM.Text.Trim();
        row["Handling"] = tbHandling.Text;
        row["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        //row["UpdateUser"] = ValidateUser2.GetUserID();
        row["UpdateUser"] = SessionManager.UserID;

        PMSAccess.UpdateDataSet(this.Connection, new string[] { this.TableName, "PMS_TaskUser"}, SessionManager.DataSet);

        if (str.Length > 0)
        {
            PMSAccess.ExecuteNonQuery(this.Connection, "update PMS_User set IsWorking=IsWorking-1 where UserId in (" + str.Remove(0, 1).ToString() + ")");
        }
        this.pnlEdit.Visible = false;
        this.pnlGrid.Visible = true;
        this.FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        tipMessage1.ShowMessage("任务完成", 5000);
    }

    protected void btnDocument_Click(object sender, EventArgs e)
    {
        string taskID = hfTaskID.Value;
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".doc");
        string outinfo = DocumentHelper.ExportDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskID);
        if (string.IsNullOrEmpty(outinfo))
        {
            ifdown.Attributes["src"] = "../SiteAdmin/DownLoadHandler.ashx?url=" +
                filePath + "&name=" + HttpUtility.UrlEncode("派工单.") + DateTime.Now.ToString("MMdd.HHmmss") + ".doc";
            //base.DownLoadFile(filePath, "派工单.doc");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000);  
        }
    }
    protected void btnListDocument_Click(object sender, EventArgs e)
    {
        string taskID = Request["TaskItemID"];
        if (string.IsNullOrEmpty(taskID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".doc");
        string outinfo = DocumentHelper.ExportDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskID);
        if (string.IsNullOrEmpty(outinfo))
        {
            ifdown.Attributes["src"] = "../SiteAdmin/DownLoadHandler.ashx?url=" +
                filePath + "&name=" + HttpUtility.UrlEncode("派工单.") + DateTime.Now.ToString("MMdd.HHmmss") + ".doc";
            //base.DownLoadFile(filePath, "派工单.doc");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000);  
        }
    }
    
    protected void btnPreTabsMenu_Click(object sender, EventArgs e)
    {

    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlGrid.Visible = true;
        pnlEdit.Visible = false;
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    protected void btnSelect_Click(object sender, EventArgs e)
    {
        if (TaskPersonItem.OnSelect != null)
        {
            TaskPersonItem.ShowWorkTime = true;
            TaskPersonItem.IsReadOnly = false;
            TaskPersonItem.OnSelect(sender, e);
            TaskPersonItem.SetGroupReadOnly(hfCurrentGroupCode.Value);
        }
    }
    protected void btnSelectGood_Click(object sender, EventArgs e)
    { 
    }

    protected void btnExportList_Click(object sender, EventArgs e)
    {
        tipMessage1.ShowMessage("", 5000);
        if (S_GroupID.SelectedValue == "")
        {
            Alert("如果要导出操作，组别必须选择");
            return;
        }
        if (S_stCreateDate.Text == "")
        {
            Alert("如果要导出操作，受理日期开始必须选择");
            return;
        }
        if (S_endCreateDate.Text == "")
        {
            Alert("如果要导出操作，受理日期截止必须选择");
            return;
        }
        DateTime st = Convert.ToDateTime(S_stCreateDate.Text);
        DateTime end = Convert.ToDateTime(S_endCreateDate.Text);

        if (st.AddMonths(3).CompareTo(end) < 0)
        {
            Alert("如果要导出操作，受理日期开始与受理日期截止不能超过三个月");
            return; 
        }

        StringBuilder sql = new StringBuilder(cmdText);
        if (!string.IsNullOrEmpty(S_Guest.Text))
        {
            sql.Append(" AND C.Guest like '%").Append(S_Guest.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_Phone.Text))
        {
            sql.Append(" AND C.Phone = '").Append(S_Phone.Text).Append("'");
        }
        if (!string.IsNullOrEmpty(S_TaskState.SelectedValue))
        {
            sql.Append(" AND a.TaskState = '").Append(S_TaskState.SelectedValue).Append("'");
        }
        if (!string.IsNullOrEmpty(S_GroupID.SelectedValue))
        {
            sql.Append(" AND a.SNGroup = '").Append(S_GroupID.SelectedValue).Append("'");
        }
        if (!string.IsNullOrEmpty(S_TaskCode.Text.Trim()))
        {
            sql.Append(" AND a.TaskCode = '").Append(S_TaskCode.Text.Trim()).Append("'");
        }
        if (!string.IsNullOrEmpty(S_stCreateDate.Text.Trim()))
        {
            sql.Append(" AND C.CreateDate >= CONVERT(varchar, '" + S_stCreateDate.Text.Trim() + "', 120 ) ");
        }
        if (!string.IsNullOrEmpty(S_endCreateDate.Text.Trim()))
        {
            sql.Append(" AND C.CreateDate <= CONVERT(varchar, '" + S_endCreateDate.Text.Trim() + "', 120 ) ");
        }
        sql.Append(" order by C.CreateDate desc");
        DataSet ds = PMSAccess.GetDataSet(this.Connection, sql.ToString());
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".doc");
        string outinfo = DocumentHelper.ExportTaskList(PMSConst.PMSTaskTrackingListTemplatePath, filePath, ds);
        if (string.IsNullOrEmpty(outinfo))
        {
            ifdown.Attributes["src"] = "../SiteAdmin/DownLoadHandler.ashx?url=" +
                filePath + "&name=" + HttpUtility.UrlEncode("任务单返还.") + DateTime.Now.ToString("MMdd.HHmmss") + ".xls";
            //base.DownLoadFile(filePath, "任务单返还.xls");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000);
        }
    }

    #region 显示领单人信息
    protected void InitGridReceiverView(string taskId)
    {
        string cmdItemsText = @"SELECT T.*,A.Username,A.GroupCode,A.Mobile,B.OrgID,D.Subject as OrgName,C.CodeName as GroupName  FROM PMS_TaskUser T inner join PMS_User A on A.UserID = T.UserID 
                    left join T_OrgUser B on B.UserID = T.UserID 
                    left join  T_CodeConfig C on C.CodeValue=A.GroupCode  AND C.Category = '" + PMSCodeCategory.PMS_BMZB + @"' 
                    left join T_OrgTree D on D.OrgID=B.OrgID where 1=1 and T.UserType='" + PMSCodeCategory.UserReceiver + "' and T.TaskID='" + taskId + "'";

        DataSet ds = PMSAccess.GetDataSet(this.Connection, cmdItemsText);
        if (ds.Tables[0].Rows.Count > 0)
        {
            hfCurrentGroupCode.Value = ds.Tables[0].Rows[0]["GroupCode"].ToString();
        }
        gridReceiverView.DataSource = ds.Tables[0];
        gridReceiverView.ShowFooter = false;
        gridReceiverView.DataBind();
    }
    #endregion
}
